<?php
/*Hachim
 * Pour charger des layouts par module,
 * ou faire un système de multitemplating
 * Ce plugin permet aussi des charger dynamiquement les models du module courant
 */
class App_Loader_Template extends Zend_Controller_Plugin_Abstract {
	protected $_layoutDir;
	protected $_defaultTemplateDir;
	protected $_layoutName;
	public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
	{
		$site = Zend_Registry::get('db')->fetchRow('SELECT * FROM core_site WHERE name = ?',$request->getParam('site'));
		Zend_Registry::set('site',$site);
		$this->_layoutDir = APPLICATION_PATH.'/../public/templates/' . $site['template'];
		$this->_defaultTemplateDir = APPLICATION_PATH.'/../public/templates/default';
		$this->_layoutName =  $site['layout'];
	}

	public function preDispatch(Zend_Controller_Request_Abstract $request){
		$currentLayout = $this->_layoutDir . '/' . $this->_layoutName . '.phtml';
		//die($currentLayout);
		$desabledLayout = $request->getParam('nolayout');
		//IMPORTANT : pour forcer la desactivation du layout
		//il faut ajouter dans l'url un param layout afin
		if($request->isXmlHttpRequest() || (isset($desabledLayout))){
			$layout->disableLayout();
		}
		else if(file_exists($currentLayout) ) {
			$layout = Zend_Layout::getMvcInstance();
			$layout->setLayoutPath($this->_layoutDir);
			$layout->setLayout($this->_layoutName);
		}
		else {			
			$layout = Zend_Layout::getMvcInstance();
			$layout->setLayoutPath($this->_defaultTemplateDir);
		}

		$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
		$viewRenderer->init();
		$view = $viewRenderer->view;
		$currentViewPath =  'modules/' . $request->getModuleName();
		$view->addScriptPath( $this->_defaultTemplateDir . '/' . $currentViewPath);
		$view->addScriptPath( $this->_layoutDir . '/' . $currentViewPath);
	}
}
